package com.jay.lang.clazz;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ThreadCls extends Thread{
	private static final AtomicInteger uniqueId = new AtomicInteger(0);
	private static final ThreadLocal<Integer> uniqueNum = new ThreadLocal<Integer>() {
		@Override
		protected Integer initialValue() {
			return uniqueId.getAndIncrement();
		}
	};

	public static int getCurrentThreadId() {
		return uniqueNum.get();
	}

	// //////////////////////////////////////////////// // Testing code...
	// //////////////////////////////////////////////////
	private static volatile boolean halt = false;

	public ThreadCls(String threadName) {
		super(threadName);
	}

	@Override
	public void run() {
		System.out.println(Thread.currentThread() + " PREHALT "
				+ getCurrentThreadId());
		while (!halt)
			try {
				TimeUnit.SECONDS.sleep(1);
			} catch (InterruptedException e) {
			}
		System.out.println(Thread.currentThread() + " POSTHALT "
				+ getCurrentThreadId());
	}

	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new ThreadCls("t1");
		Thread t2 = new ThreadCls("t2");
		Thread t3 = new ThreadCls("t3");
		Thread t4 = new ThreadCls("t4");
		t3.start();
		t1.start();
		t2.start();
		t4.start();
		TimeUnit.SECONDS.sleep(10);
		halt = true;
	}
}